In [3]:
def gensquares(N):
for i in range(N):
yield i**2
In [4]:
for x in gensquares(10):
print x
In [5]:
import random
random.randint(1,10)
Out[5]:
In [6]:
def rand_num(low,high,n):
for i in range(n+1):
yield random.randint(low, high)
In [7]:
for num in rand_num(1,10,12):
print num
In [9]:
s = 'hello'
#code here
for letter in iter(s):
print letter
A generator, utilizing a yield statement, returns an iterator object. The iterator object will yield/return a value each time it is called upon to iterate through its code. So in cases where a return statement would be used to return the entirely of a list, the generator would only return the current iteration of the list, remembering its state where it was last yielded.
In [10]:
my_list = [1,2,3,4,5]
gencomp = (item for item in my_list if item > 3)
for item in gencomp:
print item